﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Rendering;
using MyCommon.Helper;
using MyModels;

namespace MyApi.Filter
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionsFilter : IExceptionFilter
    {
        private readonly IWebHostEnvironment _env;
        private readonly ILogger<GlobalExceptionsFilter> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="env"></param>
        /// <param name="logger"></param>
        public GlobalExceptionsFilter(IWebHostEnvironment env,ILogger<GlobalExceptionsFilter> logger)
        {
            _env = env;
            _logger = logger;
        }
        /// <summary>
        /// 发生异常时候执行的方法
        /// </summary>
        /// <param name="context"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void OnException(ExceptionContext context)
        {
            var exMsg = context.Exception.Message;
            var env = _env.EnvironmentName;
            var exStack = context.Exception.StackTrace;
            var json = new MessageModel<string>();
            json.message = context.Exception.Message;
            json.status = 500;
            if (env == "Development")
            {
                json.msgDev = context.Exception.StackTrace;//堆栈信息
            }
            var res = new ContentResult();
            res.Content = JsonHelper.GetJSON<MessageModel<string>>(json);

            context.Result = res;

            //记录错误日志
            _logger.LogError(json.message+WriteLog(json.message,context.Exception));
        }

        private string WriteLog(string message,Exception ex) { 
            return string.Format("\r\n【自定义错误】：{0} \r\n【异常类型】：{1} \r\n【异常信息】：{2} \r\n【堆栈调用】：{3}",message,ex.GetType().Name,ex.Message,ex.StackTrace);
        }
    }
}
